package com.ruoyi.framework.config;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.common.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Configuration;

import java.util.Date;

/**
 * MybatisPlus配置类
 * 实现插入/修改时自动修改时间、操作人（实体类上使用 @TableField(fill = FieldFill.INSERT/INSERT_UPDATE)）
 */
@Configuration
public class MybatisPlusConfig implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        this.fillStrategy(metaObject, "createTime", new Date());
        try {
            if (ObjectUtil.isNotEmpty(SecurityUtils.getUserId())) {
                this.fillStrategy(metaObject, "createBy", SecurityUtils.getOperator());
            }
        } catch (Exception e) {

        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateTime", new Date(), metaObject);
        try {
            if (ObjectUtil.isNotEmpty(SecurityUtils.getUserId())) {
                this.setFieldValByName("updateBy", SecurityUtils.getOperator(), metaObject);
            }
        } catch (Exception e) {

        }
    }

}
